from django.shortcuts import render
from django.http import HttpResponse
from .models import *
# Create your views here.
from openpyxl import load_workbook,Workbook
import re

def account_input(request):
    context = {}
    return render(request,'gitacc/account_input.html',context)


def hasSpecial(x):
    return bool(re.search(r'[A-Za-z0-9_]',x))

def OpenExcel():
    header = ['姓名','Github账号','Gitee账号','coding.net账号']
    try:
        wb1 = load_workbook('班级账号.xlsx')
    except FileNotFoundError:
        wb1 = Workbook()
        sheet1 = wb1.active
        sheet1.title = '账号信息'
        for i in range(1,len(header)+1):
            sheet1.cell(row=1,column = i).value = header[i-1]
    finally:
        wb1.save('班级账号.xlsx')

def account_operation(request):
    account_info = dict(request.POST)
    user_name = account_info['username'][0]
    github_acc = account_info['githubacc'][0]
    gitee_acc = account_info['giteeacc'][0]
    coding_acc = account_info['codingacc'][0]

    user_list_name = User_Sql_Info.objects.all()
    name_list = [user_name.user_name for user_name in user_list_name]

    exist_name_list = Person1802.objects.all()
    exist_name = [student_name.student_name for student_name in exist_name_list]
    if user_name not in exist_name:
        context = {'error':'你输入的姓名不存在，请输入你正确的姓名！'}
        return render(request,'gitacc/account_input.html',context)
    
    if hasSpecial(user_name) == True:
        context = {'error':'姓名中不能包含数字，字符或特殊符号！'}
        return render(request,'gitacc/account_input.html',context)
    elif hasSpecial(user_name) == False:
        if user_name in name_list:
            context = {'error':'此姓名已存在，请重新输入！'}
            return render(request,'gitacc/account_input.html',context)
        else:
            user_sql_obj = User_Sql_Info.objects.create(user_name = user_name)
            user_sql_obj.account_sql_info_set.create(github_acc = github_acc,
                                                     gitee_acc = gitee_acc,
                                                     coding_acc = coding_acc)
            OpenExcel()
            wb2 = load_workbook('班级账号.xlsx')
            sheet2 = wb2['账号信息']
            row = sheet2.max_row+1
            col = sheet2.max_column +1
            sheet2['A{}'.format(row)].value = user_name
            sheet2['B{}'.format(row)].value = github_acc
            sheet2['C{}'.format(row)].value = gitee_acc
            sheet2['D{}'.format(row)].value = coding_acc
            wb2.save('班级账号.xlsx')
            context = {'suc':'提交成功！'}
            return render(request,'gitacc/account_input.html',context)


def user_input(request):
    context = {}
    return render(request,'gitacc/user_input.html',context)

def username_operation(request):
    name_dict = request.POST
    student_name = name_dict['username']
    Person1802.objects.create(student_name = student_name)
    return HttpResponse('提交成功！')



        
